package com.coldworks.coldjoke.task;

import java.io.IOException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import android.os.Message;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.coldworks.base.BaseThread;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.coldjoke.R;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.util.NetworkUtil;

public class LoginTask extends BaseThread {

	private Context context;
	private String loginUrl;
	private Handler handler;
	private DefaultHttpClient httpclient;
	private ProgressDialog progressDialog;

	public LoginTask(Context context, Handler handler, String loginUrl,
			boolean isAutoLogin) {
		this.loginUrl = loginUrl;
		this.context = context;
		this.handler = handler;
		if (!isAutoLogin) {
			showProgressDialog();
		}
	}

	@Override
	public void run() {
		HttpGet get = new HttpGet(loginUrl);
		httpclient = BaseNetworkManager.getInstance().createHttpClient(context);
		try {
			HttpResponse response = httpclient.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				Header contentEncoding = response
						.getFirstHeader("Content-Encoding");
				JSONObject jsonObject = null;
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					jsonObject = NetworkUtil.getInstance().getJsonObjectByGzip(
							response.getEntity().getContent());
				} else {
					jsonObject = NetworkUtil.getInstance().getJSONObject(
							response.getEntity().getContent());
				}
				if (jsonObject == null) {
					log.info("error-->jsonObject=null");
					Message message = handler
							.obtainMessage(UserManager.LOGIN_FAIL);
					handler.sendMessage(message);
					return;
				}
				String isLogin = jsonObject.getString("is_login");
				// log.info("test" + jsonObject);
				if (isLogin.equals("true")) {
					CookieStore cookieStore = httpclient.getCookieStore();
					UserManager.getInstance().setSessionId(cookieStore);
					UserManager.getInstance().setUserName(
							jsonObject.getString("user_name"));
					UserManager.getInstance().setUserId(
							jsonObject.getString("user_id"));
					log.info("succ");
					// Toast.makeText(context, R.string.login_success,
					// Toast.LENGTH_SHORT).show();
					Message message = handler
							.obtainMessage(UserManager.LOGIN_SUCC);
					handler.sendMessage(message);
					return;
				} else {
					log.info("failed");
					// Toast.makeText(context, R.string.login_failed,
					// Toast.LENGTH_SHORT).show();
					Message message = handler
							.obtainMessage(UserManager.LOGIN_FAIL);
					handler.sendMessage(message);
					return;
				}
			} else {
				log.info("error net-->staus code ="
						+ response.getStatusLine().getStatusCode());
				Message message = handler.obtainMessage(UserManager.LOGIN_FAIL);
				handler.sendMessage(message);
				return;
			}
		} catch (ClientProtocolException e) {
			log.error("", e);
			Message message = handler.obtainMessage(UserManager.LOGIN_FAIL);
			handler.sendMessage(message);
			return;
		} catch (IOException e) {
			log.error("", e);
			Message message = handler.obtainMessage(UserManager.LOGIN_FAIL);
			handler.sendMessage(message);
			return;
		} catch (JSONException e) {
			log.error("", e);
			Message message = handler.obtainMessage(UserManager.LOGIN_FAIL);
			handler.sendMessage(message);
			return;
		} finally {
			closeProgressDialog();
		}
	}

	private void showProgressDialog() {
		progressDialog = new ProgressDialog(context);
		progressDialog.setMessage(context.getResources().getString(
				R.string.login_ing));
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(true);
		progressDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				UserManager.getInstance().cancleLoginTask();
			}
		});
		progressDialog.show();
	}

	private void closeProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
	}
}
